package system

import (
	"context"
	"encoding/json"
	"fmt"
	"gf-assistant/internal/common/factory"
	"gf-assistant/internal/system/parameter"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"reflect"
	"strings"
)

type OrgDao struct{}

func init() {
	orgDao := OrgDao{}
	factory.Put(reflect.TypeOf(orgDao).String(), &orgDao)
}
func (dao *OrgDao) DB() gdb.DB {
	return g.DB()
}
func (dao *OrgDao) GetOrgCombox(ctx context.Context, req *parameter.GetOrgComboxReq) (orgs []*parameter.OrgComboxRes) {

	sql := `
		  SELECT t.ORG_ID as Id, t.PARENT_ID as PId,t.ORG_NAME as Title
		  FROM ORG_INFO t
		  WHERE t.ENABLE_STATUS=1
		  ORDER BY t.PARENT_ID ASC
		  `
	resultList, err := g.DB().GetAll(ctx, sql)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		org := parameter.OrgComboxRes{}
		err = json.Unmarshal([]byte(v.Json()), &org)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		orgs = append(orgs, &org)
	}
	return orgs
}
func (dao *OrgDao) GetOrgTree(ctx context.Context, req *parameter.GetOrgTreeReq) (orgs []*parameter.OrgTreeRes) {
	sql := `
		  SELECT t.ORG_ID as Id, t.PARENT_ID as PId,t.ORG_NAME as Title, t.REMARK as Remark
		  FROM ORG_INFO t
		  WHERE t.ENABLE_STATUS=1
		  ORDER BY t.PARENT_ID ASC
		  `
	resultList, err := g.DB().GetAll(ctx, sql)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		org := parameter.OrgTreeRes{}
		err = json.Unmarshal([]byte(v.Json()), &org)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		orgs = append(orgs, &org)
	}
	return orgs
}
func (dao *OrgDao) ListOrg(ctx context.Context, req *parameter.ListOrgReq) (orgs []*parameter.GetOrgRes) {
	parameters := make([]interface{}, 0)
	sql := `
		  select t.ORG_ID as OrgId,t.PARENT_ID as ParentId, t.ORG_NAME as OrgName,t.REMARK as remark,
		         t.ENABLE_STATUS AS EnableStatus,
		         ELT(FIELD(t.ENABLE_STATUS, 0, 1),'无效','有效')AS EnableStatusName,
		         c.NICK_NAME as CreatedUserName,m.NICK_NAME as UpdatedUserName,
				 DATE_FORMAT(t.CREATE_TIME,'%Y-%m-%d %T') as CreatedTime,
				 DATE_FORMAT(t.UPDATE_TIME,'%Y-%m-%d %T') as UpdatedTime
		  from ORG_INFO t 
		  left join SYS_USER c on t.CREATE_USER=c.USER_ID
		  left join SYS_USER m on t.UPDATE_USER=m.USER_ID
		  where t.PARENT_ID>0
		  `
	if req.ParentId > 0 {
		sql = sql + " and t.PARENT_ID=?" + "\n"
		parameters = append(parameters, req.ParentId) //父机构
	}
	if req.EnableStatus > -1 {
		sql = sql + " and t.ENABLE_STATUS=?" + "\n"
		parameters = append(parameters, req.EnableStatus) //父机构
	}
	if req.OrgName != "" {
		sql = sql + " and t.ORG_NAME like ?\n"
		parameters = append(parameters, "%"+strings.TrimSpace(req.OrgName)+"%") //机构名称
	}
	sql = sql + " order by t.UPDATE_TIME,t.ENABLE_STATUS desc \n"
	resultList, err := g.DB().GetAll(ctx, sql, parameters)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		org := parameter.GetOrgRes{}
		err = json.Unmarshal([]byte(v.Json()), &org)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		orgs = append(orgs, &org)
	}
	return orgs
}
func (dao *OrgDao) CountOrg(ctx context.Context, req *parameter.ListOrgReq) (count int64) {
	parameters := make([]interface{}, 0)
	sql := `
		  select count(t.ORG_ID) orgCount
		  from ORG_INFO t 
		  where t.PARENT_ID>0
		  `
	if req.ParentId > 0 {
		sql = sql + " and t.PARENT_ID=?" + "\n"
		parameters = append(parameters, req.ParentId) //父机构
	}
	if req.EnableStatus > -1 {
		sql = sql + " and t.ENABLE_STATUS=?" + "\n"
		parameters = append(parameters, req.EnableStatus) //父机构
	}
	if req.OrgName != "" {
		sql = sql + " and t.ORG_NAME like ?\n"
		parameters = append(parameters, "%"+strings.TrimSpace(req.OrgName)+"%") //机构名称
	}
	one, err := g.DB().GetOne(ctx, sql, parameters)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	count = gconv.Int64(one.Map()["orgCount"])
	return count
}
func (dao *OrgDao) CountByOrgName(ctx context.Context, parentId uint, orgName string) uint {
	parameters := make([]interface{}, 0)
	sql := `
		  select count(t.ORG_ID) orgCount
		  from ORG_INFO t 
		  where t.PARENT_ID=? and t.ORG_NAME=?
		  `
	parameters = append(parameters, parentId)                   //父机构
	parameters = append(parameters, strings.TrimSpace(orgName)) //机构名称
	one, err := g.DB().GetOne(ctx, sql, parameters)
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
	}
	count := gconv.Uint(one.Map()["orgCount"])
	return count
}
func (dao *OrgDao) CreateOrg(tx gdb.TX, req *parameter.SaveOrgReq) (res *parameter.SaveOrgRes) {
	parameters := make([]interface{}, 0)
	sql := `
			insert into ORG_INFO(PARENT_ID,ORG_NAME,ENABLE_STATUS,REMARK,CREATE_TIME,CREATE_USER,UPDATE_TIME,UPDATE_USER)
			values (?,?,1,?,now(),?,now(),?)
		  `
	parameters = append(parameters, req.ParentId, req.OrgName, req.Remark, req.GetOperatorId(), req.GetOperatorId())

	result, err := tx.Exec(sql, parameters)
	if err != nil {
		fmt.Printf("insert org faied, error:[%v]", err.Error())
	}
	insertId, err := result.LastInsertId()
	return &parameter.SaveOrgRes{OrgId: gconv.Uint(insertId)}
}
func (dao *OrgDao) UpdateOrg(tx gdb.TX, req *parameter.SaveOrgReq) {
	parameters := make([]interface{}, 0)
	sql := `
			update ORG_INFO set 
				ORG_NAME=?,
				REMARK=?,
				ENABLE_STATUS=?,
				UPDATE_TIME=now(),
				UPDATE_USER=?
			where ORG_ID=?
		  `
	parameters = append(parameters, req.OrgName, req.Remark, req.EnableStatus, req.GetOperatorId(), req.OrgId)
	_, err := tx.Exec(sql, parameters)
	if err != nil {
		panic("修改机构失败")
	}
}
